//
//  TransferTableViewController.swift
//  甜言蜜语
//
//  Created by 王剑伟 on 16/7/14.
//  Copyright © 2016年 wl. All rights reserved.
//

import UIKit

class TransferTableViewController: UITableViewController, HeardDelegate {

    /// 当前频道
    var channel: String!
    /// 当前频道的url
    var channelUrl: String!
    
    var modelList: [TransferModel]? {
        didSet {
            self.tableView.reloadData()
        }
    }
    var hasSelected: Bool = false
    var newsTableHeadViewController = NewsHeadViewController()
    var fontSize: CGFloat!
    var page = 0
    var selectedPage = 0
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.tableView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(TransferTableViewController.requestInfo))
        self.tableView.mj_header.beginRefreshing()
        publicMethod.hiddleExtendCellForTableView(self.tableView)
        
         self.tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: #selector(TransferTableViewController.nextRequestInfo))
        self.newsTableHeadViewController.url = self.channelUrl
        
        self.addChildViewController(self.newsTableHeadViewController)
        self.tableView.tableHeaderView = self.newsTableHeadViewController.view
        
        self.newsTableHeadViewController.delegate = self
        
    }

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        if ApplicationDelegate.isLogin(){
            let phone = publicMethod.userName()
            let pass = publicMethod.passWord()
            let token = publicMethod.token()
            DataTool.login(phone, pass: pass, token: token, completionHandler: { (newModel) in
                guard let newDataes = newModel else {
                    return
                }
                print(newDataes)
                
            })
            
        }
        self.tabBarController?.tabBar.hidden = false
        let str = ApplicationDelegate.fontSize()
        self.fontSize  =  CGFloat ( (str as NSString).floatValue)

    }
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
   

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        if let count = self.modelList?.count {
            return count
        }
        
        return 0
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("TransferTableViewCell", forIndexPath: indexPath) as! TransferTableViewCell

        // Configure the cell...
        let model = self.modelList![indexPath.row]
        cell.icon.sd_setImageWithURL(NSURL(string: model.imgsrc), placeholderImage: UIImage(named: "placeholder"))
        cell.title.text = model.name
        cell.title.font = UIFont.systemFontOfSize(self.fontSize)
        cell.address.text = model.address
        cell.type.text = model.type
        cell.describe.text = model.newold
        cell.price.text = model.price
        cell.time.text = publicMethod.computationTimeDifference(model.ptime)

        return cell
    }
    
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if(cell.respondsToSelector(Selector("setSeparatorInset:"))) {
            cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0)
        }
        if(cell.respondsToSelector(Selector("setLayoutMargins:"))) {
            cell.layoutMargins = UIEdgeInsetsMake(0, 0, 0, 0)
        }
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let model = self.modelList![indexPath.row]
        if model.type == "整店" {
            
            let vc = self.storyboard?.instantiateViewControllerWithIdentifier("TransferShopDetailTableViewController") as! TransferShopDetailTableViewController
            vc.id = modelList![indexPath.row].id
            vc.type = modelList![indexPath.row].type
            self.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(vc, animated: true)
            self.hidesBottomBarWhenPushed = false
            
        } else {
            
            let vc = self.storyboard?.instantiateViewControllerWithIdentifier("TransferGoodsDetailTalbeViewController") as! TransferGoodsDetailTalbeViewController
            vc.id = modelList![indexPath.row].id
            vc.type = modelList![indexPath.row].type
            self.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(vc, animated: true)
            self.hidesBottomBarWhenPushed = false
        }
    }
 
    // MARK: - HeardDelegate
    func onHeightChange(newView: UIView) {
        self.tableView.tableHeaderView = newView
    }
    func setContentViewControllerWithInfo() -> Void{
        
    }
    func setContentTransferViewControllerWithInfo() -> Void{
        //self.modelList = cellInfo
        self.hasSelected = true
        self.requestInfo()
        
    }
    func setContentJoninUsViewControllerWithInfo() -> Void{
        
    }
    func setContentMXQYViewConreollerWithInfo() -> Void{
        
    }
    func setContentZYCPViewControllerWithInfo() -> Void{
        
    }
    func CyclePictureViewSelected(url: String){
//        let vc = self.storyboard?.instantiateViewControllerWithIdentifier("DetailTaoboaAndliveVideoVC") as! DetailTaoboaAndliveVideoVC
//        
//        vc.urlStr = "https://www.taobao.com"
//        
//        self.navigationController?.pushViewController(vc, animated: true)
    }
    /**
     下拉刷新，加载最新数据
     */
    func requestInfo() {
        self.tableView.mj_footer.resetNoMoreData()
        self.page = 0
        if self.hasSelected == false{
           
            let urlStr = String(format: "%@infomationjson/\(self.channelUrl)",BaseUrl)
            DataTool.loadTransferData(urlStr,completionHandler: { (newsArray) -> Void in
                self.tableView.mj_header.endRefreshing()
                guard let newDataes = newsArray else {
                    return
                }
                self.modelList = newDataes
            })
        }else{
            self.selectedPage = 0
            DataTool.dropMenuScreen_ynzr(self.newsTableHeadViewController.type!, area: self.newsTableHeadViewController.area!, shaixuan: self.newsTableHeadViewController.shaixuan!,page: String(self.selectedPage), completionHandler: { (newsArray) -> Void in
                self.tableView.mj_header.endRefreshing()
                guard let newDataes = newsArray else {
                    return
                }
                print(newDataes)
                self.modelList = newDataes
            })

        }
        
       
    }
    /**
     上拉刷新，加载最新数据
     */
    func nextRequestInfo(){
        self.page += 1
        if hasSelected == false{
            let urlStr = String(format: "%@transfer/dosel/fenye/\(self.page)",BaseUrl)
            DataTool.loadNextTrandferEx(String(self.page),urlStr: urlStr, completionHandler: { (newsArray) -> Void in
                
                guard let newDataes = newsArray else {
                    return
                }
                if newDataes.count == 0 {
                    self.tableView.mj_footer.endRefreshingWithNoMoreData()
                } else {
                    self.modelList! += newDataes
                    self.tableView.mj_footer.endRefreshing()
                }
                
            })

        }else{
            self.selectedPage += 1
            DataTool.dropMenuScreen_ynzr(self.newsTableHeadViewController.type!, area: self.newsTableHeadViewController.area!, shaixuan: self.newsTableHeadViewController.shaixuan!,page: String(self.selectedPage), completionHandler: { (newsArray) -> Void in
                
                guard let newDataes = newsArray else {
                    return
                }
                if newDataes.count == 0 {
                    self.tableView.mj_footer.endRefreshingWithNoMoreData()
                } else {
                   self.tableView.mj_footer.endRefreshing()
                    print(newDataes)
                    self.modelList! += newDataes
                }
                
            })

            
        }
        
        
    }
    func onSendInfoClick() -> Void {
        if ApplicationDelegate.isLogin(){
            let vc = self.storyboard?.instantiateViewControllerWithIdentifier("TransferChoosePublishTableViewController") as! TransferChoosePublishTableViewController
            self.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(vc, animated: true)
            self.hidesBottomBarWhenPushed = false
        }else{
            let sb = UIStoryboard(name: "Login", bundle: nil)
            let vc = sb.instantiateViewControllerWithIdentifier("LoginViewController")
            self.navigationController?.pushViewController(vc, animated: true)
        }
        
    }
}
